﻿@model CallCenter.Data.Models.ContactGridViewModel

@{
    ViewBag.Title = "ContactHistory";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
    <div class="divCenter">
        <input type="button" value="AddCompany" onclick="@("window.location.href='" + @Url.Action("CompanyHistory", "AddCompany") + "'")    ;" />
        <input type="button" value="AddProduct" onclick="@("window.location.href='" + @Url.Action("ProductHistory", "AddProduct") + "'")    ;" />
    </div>
</div>
<div class="container container-table">
    <div class="row vertical-center-row">
        <div class="text-center col-md-4-col-offset-4">
            <div id="example">
                <div class="demo-section k-content">
                    <h4>Look Up Contact Information</h4>
                    <input id="contact" style="width: 50%;" />
                    <p class="demo-hint">
                        Start typing to find a contact. E.g. "Ann"
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="SavedResult in"></div>
<button id="dirty" class="k-button">Get Filtered Results</button>
<button id="all" class="k-button">All</button>
@*<p>
    <button id="btnGetResults">Get Filtered Results</button>
</p>*@
<div id="addcontactGrid"></div>
<div id="ContactCompanyGrid"></div>
<div id="ContactDetailGrid"></div>
<div id="MessageGrid"></div>
<input type="hidden" id="userLoggedIn" value="@User.Identity.Name" />


<script type="text/javascript" src="~/Scripts/CallCenter/ScratchPadAutoComplete.js"></script>





<script id="delete-confirmation" type="text/x-kendo-template">

    <p class="delete-message">“Are you sure you want to delete the records?”</p>

    <button class="delete-confirm k-button btn btn-default">Yes</button>

    <button class="delete-cancel  k-button btn btn-default">No</button>

</script>
<style>
    .someCssColorClass {
        color: red !important;
    }
</style>

<style>
    .customClass {
        background: green;
    }

    .SavedResult {
        width: 800px;
        margin: 0 auto;
        font-size: 15px;
    }
</style>

<script>
    function showCompany(contactId, e) {
        $('#ContactCompanyGrid').show();
        $('#addcontactGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");
        $("#MessageGrid").hide();
        $('#ContactDetailGrid').hide();
        $('#ContactCompanyGrid').empty();
        var gridInEditMode = false;
        var dataSource1 = new kendo.data.DataSource({

            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../AddCompanyToContacts/GetCompaniesofContact",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify({ id: contactId }),
                        success: function (data) {

                            options.success(data);
                        },
                        error: function (request, status, error) {
                            alert(request.responseText);
                        }
                    });
                },

                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }
            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        company:
                            {
                                type: "string"
                            },
                        phone:
                            {
                                type: "string"
                            },
                        address:
                       {
                           type: "string"
                       },
                        contactId:
                      {
                          type: "int"
                      },
                        companyId:
                      {
                          type: "int"
                      },
                        error: function (a) {
                            debugger;
                            $('#CompanyContactGrid').data("kendoGrid").cancelChanges();
                        },

                    }
                }
            }
        });
        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({
                value: new Date()
            });
        }

        var companydatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    debugger;
                    $.ajax({
                        type: "GET",
                        url: "../ContactMessages/GetAllCompanies",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        $("#ContactCompanyGrid").kendoGrid({
            dataSource: dataSource1,
            scrollable: true,
            height: "250px",
            toolbar: ["excel"], //, "save", "cancel"],
            excel: {
                allPages: true,
                fileName: "ContactCompanyExport.xlsx"
            },
            pageable: true,
            height: 300,
            columns: [

          { field: "company", title: "Company Name", editor: companyDropDownEditor, filterable: false, width: "8em" },
          { field: "phone", title: "Phone", width: "8em" },
          { field: "address", title: "Address", filterable: false, width: "8em" },

          {
              title: "&nbsp;",
              width: "25em",
              command: [

                  "edit",
                  {
                      name: "Delete",
                      click: function (e) {
                          debugger;
                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          ////}
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            edit: function (e) {
                e.container.find(".k-edit-label:nth-child(3)").hide();
                e.container.find(".k-edit-field:nth-child(3)").hide();
                e.container.find(".k-edit-label:nth-child(4)").hide();
                e.container.find(".k-edit-field:nth-child(4)").hide();
                e.container.find(".k-edit-label:nth-child(5)").hide();
                e.container.find(".k-edit-field:nth-child(5)").hide();
                e.container.find(".k-edit-label:nth-child(6)").hide();
                e.container.find(".k-edit-field:nth-child(6)").hide();

                gridInEditMode = true;
            },
            selectable: true,
            cancel: function () {

                gridInEditMode = false;
            }
        });
        function companyDropDownEditor(container, options) {
            $('<input data-text-field="company" data-value-field="id"  data-bind="value:companyId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                dataTextField: "company",
                dataSource: companydatasource
            });
        }
        dataSource1.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {

            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        $(".close").click(function () {
            debugger;
            $(this).parent().removeClass('in');
        });
        function deleteTopicConfirmation(e, widget) {
            var grid = $('#ContactCompanyGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px"
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {
                        grid.dataSource.remove(currentRowData);
                        grid.dataSource.sync();
                    }
                    $(this).closest("[data-role=window]").kendoWindow("close");

                });
        }
    }
</script>

<script>
    function showDetails(contactId, e) {
        $('#ContactDetailGrid').show();
        $('#addcontactGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");
        $('#ContactCompanyGrid').hide();
        $("#MessageGrid").hide();
        $('#ContactDetailGrid').empty();

        var gridInEditMode = false;
        var dataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../ContactDetail/GetContactDetails",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        cache: false,
                        data: JSON.stringify({ id: contactId }),
                        success: function (data) {

                            options.success(data);
                        },
                        error: function (request, status, error) {
                            alert(request.responseText);
                        }
                    });
                },
                create: function (options) {
                    debugger;
                    var ContactDetailsVM = new Object();
                    ContactDetailsVM.id = options.data.id;
                    if (options.data.companyId)
                        ContactDetailsVM.companyId = options.data.companyId.id;
                    if (options.data.officeId)
                        ContactDetailsVM.officeId = options.data.officeId.officeId;
                    if (options.data.contactTypeId)
                        ContactDetailsVM.contactTypeId = options.data.contactTypeId.id;

                    if (options.data.title)
                        ContactDetailsVM.title = options.data.title.id

                    ContactDetailsVM.notes = options.data.notes;
                    ContactDetailsVM.startDate = options.data.startDate;
                    ContactDetailsVM.endDate = options.data.endDate;
                    ContactDetailsVM.faxNumber = options.data.faxNumber;
                    ContactDetailsVM.email = options.data.email;
                    ContactDetailsVM.workPhone = options.data.workPhone;
                    ContactDetailsVM.homePhone = options.data.homePhone;
                    ContactDetailsVM.timeZone = options.data.timeZone;
                    ContactDetailsVM.contactId = contactId;

                    $.ajax({
                        type: "POST",
                        url: "../ContactDetail/CreateContactDetails",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(ContactDetailsVM),

                        success: function (data) {
                            debugger;
                            options.success(data);
                        }
                    });
                },
                update: function (options) {
                    debugger;

                    var ContactDetailsVM = new Object();
                    ContactDetailsVM.id = options.data.id;
                    ContactDetailsVM.companyId = options.data.companyId;
                    ContactDetailsVM.officeId = options.data.officeId;
                    ContactDetailsVM.contactTypeId = options.data.contactTypeId;
                    ContactDetailsVM.title = options.data.title

                    ContactDetailsVM.notes = options.data.notes;
                    ContactDetailsVM.startDate = options.data.startDate;
                    ContactDetailsVM.endDate = options.data.endDate;
                    ContactDetailsVM.faxNumber = options.data.faxNumber;
                    ContactDetailsVM.email = options.data.email;
                    ContactDetailsVM.workPhone = options.data.workPhone;
                    ContactDetailsVM.homePhone = options.data.homePhone;
                    ContactDetailsVM.timeZone = options.data.timeZone;
                    ContactDetailsVM.contactId = contactId;
                    $.ajax({
                        type: "POST",
                        url: "../ContactDetail/UpdateContactDetails",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(ContactDetailsVM),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                },
                destroy: function (options) {
                    debugger;
                    $.ajax({
                        type: "POST",
                        url: "../ContactDetail/DeleteContactDetails",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }
            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        company:
                            {
                                type: "string",
                                validation: { required: true },
                            },
                        companyoffice:
                          {
                              type: "string",
                              defaultValue: "None"
                          },
                        code:
                            {
                                type: "string",
                                validation: { required: true }
                            },
                        companyType:
                            {
                                type: "string",
                                validation: { required: true }
                            },
                        workPhone:
                            {
                                type: "string"
                            },
                        homePhone:
                           {
                               type: "string"
                           },
                        faxNumber:
                          {
                              type: "string"
                          },
                        office:
                       {
                           type: "string"
                       },
                        officeId:
                     {
                         type: "int"
                     },

                        //                        companyId:{
                        //                        type:"int"
                        //},

                        email:
                       {
                           type: "string",
                           validation: { required: true }
                       },
                        timeZone:
                      {
                          type: "string",
                        defaultValue: "ET",

                      },
                        notes:
                            {
                                type: "string"
                            },
                        startDate:
                      {
                          type: "date",
                          editable: false
                      },
                        endDate:
                       {
                           type: "date",
                           //  validation: { required: true },
                           nullable: true,
                           value: "",

                           defaultOption: null
                       },
                        error: function (a) {

                            $('#ContactDetailGrid').data("kendoGrid").cancelChanges();
                        },


                    }
                }
            }
        });
        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({
                value: new Date()
            });
        }

        var companydatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    debugger;
                    $.ajax({
                        type: "GET",
                        url: "../ContactMessages/GetAllCompanies",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var officedatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    //var ContactDetailsVM = new Object();

                    //    ContactDetailsVM.companyId = options.data.companyId.id;
                    $.ajax({
                        type: "GET",
                        url: "../CompanyOffice/GetAllCompanyOffice",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var contactTypedataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",
                        url: "../ContactDetail/GetAllContactTypes",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "Value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var jobdataSource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",
                        url: "../ContactDetail/GetAllJobTitles",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "Value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        $("#ContactDetailGrid").kendoGrid({
            dataSource: dataSource,
            scrollable: true,
            height: "250px",
            toolbar: [{ name: "create", text: "Add ContactDetails" }, "excel"], //, "save", "cancel"],
            excel: {
                fileName: "ContactDetailsExport.xlsx"
            },
            pageable: true,
            height: 300,
            columns: [
  //{ field: "company", title: "AddDetailsTo", filterable: false, editor: companyDropDownEditor, width: "8em" },
          { field: "company", title: "Company Name *", filterable: false, editor: companyDropDownEditor, width: "8em" },
             { field: "companyoffice", title: "Branch Office ", editor: officeDropDownEditor, width: "8em" },
          { field: "companyType", title: "Contact Type *", editor: contactTypeDropDownEditor, filterable: false, width: "8em" },
          { field: "timeZone", title: "Time Zone ", editor: timeZoneDropDownEditor, width: "8em" },
            { field: "email", title: "Email *", width: "8em" },
              { field: "code", title: "Job Title *", editor: jobDropDownEditor, width: "8em" },
               { field: "workPhone", title: "Work Phone", width: "8em" },
                { field: "homePhone", title: "Home Phone", hidden: true, width: "8em" },
                  { field: "faxNumber", title: "Fax", hidden: true, width: "8em" },


                {
                    field: "startDate", title: "Start Date *", filterable: false, format: "{0:MM/dd/yyyy}", width: "12em", template: "#= kendo.toString(kendo.parseDate(startDate, 'yyyy-MM-dd'), 'MM/dd/yyyy') #",
                   
                },
                  {
                      field: "endDate", title: "End Date", filterable: false, format: "{0:MM/dd/yyyy HH:mm tt}",
                      editor: dateTimeEditor, width: "10em",
                      filterable: {
                          ui: "datetimepicker"
                      }
                  },


                    {
                        field: "notes", title: "Notes", width: "200px", editor: function (container, options) {
                            $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
                        }
                    },

          {
              title: "&nbsp;",
              width: "20em",
              command: [

                  "edit",
                  {
                      name: "Delete",
                      click: function (e) {
                          debugger;
                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          ////}
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },

            editable: "popup",
            edit: function (e) {



                $('<a href="../AddJobTitle/JobHistoryHistory"><img id="theImg" src="https://cdn0.iconfinder.com/data/icons/16x16-free-toolbar-icons/16/13.png" /></a>').insertAfter($("#jobtitleId").parent());


                gridInEditMode = true;
            },


            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,
            cancel: function () {
                gridInEditMode = false;
            }
        });
        $("#ContactDetailGrid").kendoTooltip({
            filter: "td:nth-child(12)", //this filter selects the second column's cells
            position: "left",
            content: function (e) {
                var target = e.target;
                return $(target).text();

            }
        }).data("kendoTooltip");


        function companyDropDownEditor(container, options) {
            $('<input data-text-field="company" data-value-field="id"  data-bind="value:companyId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                optionLabel: "select a company",
                dataTextField: "company",
                dataSource: companydatasource,
                change: function (e) {
                    console.log(e.sender.value());
                    //console.log(e.sender.text());
                    //alert(e);
                    $.ajax({
                        type: "POST",
                        url: "../CompanyOffice/GetCompanyOfficeByCompanyId",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: e.sender.value() }),
                        success: function (data) {
                            officedatasource.data(data)
                        }
                    });
                }
            });
            $('<span class="k-invalid-msg" data-for="company"></span>').appendTo(container);
        }
        function officeDropDownEditor(container, options) {

            $('<input id="officeId" data-text-field="companyoffice" data-value-field="officeId"  data-bind="value:officeId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "officeId",
                dataTextField: "companyoffice",
                optionLabel: "select an office",
                dataSource: officedatasource
            });
            $('<span class="k-invalid-msg" data-for="companyoffice"></span>').appendTo(container);
        }

        function contactTypeDropDownEditor(container, options) {
            $('<input data-text-field="companyType" data-value-field="id" data-bind="value:contactTypeId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                optionLabel: "select a company",
                dataTextField: "companyType",
                dataSource: contactTypedataSource
            });
            $('<span class="k-invalid-msg" data-for="companyType"></span>').appendTo(container);
        }
        function jobDropDownEditor(container, options) {
            $('<input  id="jobtitleId" data-text-field="code" data-value-field="id" data-bind="value:title"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                dataTextField: "code",
                optionLabel: "select a job title",
                dataSource: jobdataSource
            });
            $('<span class="k-invalid-msg" data-for="code"></span>').appendTo(container);
        }
        function timeZoneDropDownEditor(container, options) {
            $('<input id="timeZoneId" data-text-field="dataText" data-value-field="dataText"  data-bind="value:' + options.field + '"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataSource: { data: [{ dataText: "ET", dataValue: "1" }, { dataText: "CT", dataValue: "2" }, { dataText: "PT", dataValue: "3" }, { dataText: "KT", dataValue: "4" }] },
                optionLabel: "select timezone",


            });
            $('<span class="k-invalid-msg" data-for="dataText"></span>').appendTo(container);
        }
        dataSource.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {


            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                $("#saveConfirm").addClass('in');
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });

        function deleteTopicConfirmation(e, widget) {
            var grid = $('#ContactDetailGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px"
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
    }
</script>

<script type="text/javascript">
    var IsAssEmpChecked = false, assignedEmployeeIdVar = null; assignedProductId = null;

    var editedUID = "";

    function UpdateIdinIsAssEmp(e) {
        IsAssEmpChecked = true;
    }

    function showCompanyMessages(contactId, e) {
        var gridInEditMode = false;
        $('#MessageGrid').show();
        $('#addcontactGrid tr.k-state-selected').removeClass('k-state-selected');
        var row = $(e).closest("tr");
        row.addClass("k-state-selected");

        $('#ContactDetailGrid').hide();
        $("#ContactCompanyGrid").hide();
        $('#MessageGrid').empty();


        var dataSource3 = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../ContactMessages/GetContactMSG",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: contactId }),

                        success: function (data) {
                            debugger;
                            options.success(data);
                        },

                        error: function (request, status, error) {

                            alert(request.responseText);
                        }
                    });
                },
                create: function (options) {
                    debugger;
                    var ContactCompanyMessageVM = new Object();
                    ContactCompanyMessageVM.id = options.data.id;
                    ContactCompanyMessageVM.contactId = contactId;
                    ContactCompanyMessageVM.userID = options.data.userID;
                    //if (options.data.clientID)
                    ContactCompanyMessageVM.clientID = options.data.clientID;//.id;

                    if (options.data.communicationTypeID)
                        ContactCompanyMessageVM.communicationTypeID = options.data.communicationTypeID.id;
                    ContactCompanyMessageVM.subject = options.data.subject;
                    if (options.data.productID)
                        ContactCompanyMessageVM.productID = options.data.productID.id;
                    ContactCompanyMessageVM.notes = options.data.notes;
                    ContactCompanyMessageVM.followUpdate = options.data.followUpdate;
                    if (options.data.statusID)
                        ContactCompanyMessageVM.statusID = options.data.statusID.status;
                    if (options.data.officeId)
                        ContactCompanyMessageVM.officeId = options.data.officeId.officeId;
                    ContactCompanyMessageVM.emailTo = options.data.emailTo;
                    ContactCompanyMessageVM.phone = options.data.phone;
                    ContactCompanyMessageVM.communicationDate = options.data.communicationDate;
                    ContactCompanyMessageVM.CommEmployeeIds = options.data.CommEmployeeIds;
                    ContactCompanyMessageVM.logInOwner = options.data.logInOwner;
                    ContactCompanyMessageVM.inOrOut = options.data.inOrOut;

                    debugger;
                    $.ajax({
                        type: "POST",
                        url: "../ContactMessages/CreateContactMessages",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(ContactCompanyMessageVM),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                },
                update: function (options) {

                    var ContactCompanyMessageVM = new Object();
                    ContactCompanyMessageVM.id = options.data.id;
                    ContactCompanyMessageVM.contactId = contactId;
                    ContactCompanyMessageVM.userID = options.data.userID;
                    ContactCompanyMessageVM.clientID = options.data.clientID;//.id;

                    ContactCompanyMessageVM.communicationTypeID = options.data.communicationTypeID
                    ContactCompanyMessageVM.subject = options.data.subject;

                    ContactCompanyMessageVM.productID = options.data.productID
                    ContactCompanyMessageVM.notes = options.data.notes;
                    ContactCompanyMessageVM.followUpdate = options.data.followUpdate;
                    ContactCompanyMessageVM.statusID = options.data.statusID
                    ContactCompanyMessageVM.officeId = options.data.officeId
                    ContactCompanyMessageVM.emailTo = options.data.emailTo;
                    ContactCompanyMessageVM.phone = options.data.phone;
                    ContactCompanyMessageVM.communicationDate = options.data.communicationDate;
                    ContactCompanyMessageVM.CommEmployeeIds = options.data.CommEmployeeIds;
                    ContactCompanyMessageVM.logInOwner = options.data.logInOwner;
                    $.ajax({
                        type: "POST",
                        url: "../ContactMessages/UpdateContactMessages",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify(ContactCompanyMessageVM),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                destroy: function (options) {
                    $.ajax({
                        type: "POST",
                        url: "../ContactMessages/DeleteCompanyContactMessages",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ id: options.data.id }),

                        success: function (data) {

                            options.success(data);
                        }
                    });
                },
                parameterMap: function (options) {
                    return kendo.stringify(options); // kendo.stringify serializes to JSON string
                }
            },
            schema: {
                model: {
                    id: "id",
                    fields: {
                        id: {
                            editable: false, nullable: true,
                            type: "int"
                        },
                        followUpdate: {
                            type: "date",

                            nullable: true,
                            value: "",
                            defaultOption: null
                        },
                        communicationDate: {
                            type: "date",

                            nullable: true,
                            value: "",
                            defaultOption: null

                        },
                        company: {
                            type: "string"
                        },
                        contactID: {
                            type: "string"
                        },
                        companyoffice: {
                            type: "string"
                        },
                        product: {
                            type: "string"
                        },
                        logInOwner:
                          {
                              defaultValue: "@User.Identity.Name",
                              type: "string"
                          },
                        commVia: {
                            type: "string"
                        },
                        contactname:
                             {
                                 type: "string"
                             },
                        InvoluedEname:
                           {
                               type: "string"
                           },

                        assignedEmployeeID: {
                            type: "string"
                        },

                        email: {
                            type: "string"
                        },

                        phone: {
                            type: "string"
                        },

                        statusName: {
                            type: "string",
                            validation: { required: true }
                        },

                        subject: {
                            type: "string"
                        },

                        notes: {

                            type: "string",

                        },
                        officeId:
                        {
                            type: "int"
                        },
                        name:
                            {
                                type: "string"
                            },

                        error: function (a) {
                            $('#MessageGrid').data("kendoGrid").cancelChanges();
                        },

                    }
                }
            }
        });
        var companydatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    debugger;
                    $.ajax({
                        type: "GET",
                        url: "../ContactMessages/GetAllCompanies",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var productdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ScratchPad/GetAllProducts",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var statusdatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ScratchPad/GetStatus",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var contactedviadatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ScratchPad/GetAllCommunicationMedium",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var officedatasource = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../CompanyOffice/GetAllCompanyOffice",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        var involuedEmployees = new kendo.data.DataSource({
            transport: {
                read: function (options) {
                    $.ajax({
                        type: "GET",

                        url: "../ProductRequestGrid/GetInvlouedEmployees",
                        contentType: "application/json; charset=utf-8",
                        dataType: 'json',
                        data: JSON.stringify({ key: "value" }),
                        success: function (data) {
                            options.success(data);
                        }
                    });
                }
            }
        });
        function dateTimeEditor(container, options) {
            $('<input data-text-field="' + options.field + '" data-value-field="' + options.field + '" data-bind="value:' + options.field + '" data-format="' + options.format + '"/>')
            .appendTo(container)
            .kendoDateTimePicker({
                value: new Date()
            });
        }
        $("#MessageGrid").kendoGrid({
            dataSource: dataSource3,
            scrollable: true,
            height: "250px",
            toolbar: [{ name: "create", text: "Add New Messages" }, "excel"], //, "save", "cancel"],
            excel: {
                allPages: true,
                fileName: "ContactsMessagesExport.xlsx"
            },
            pageable: true,
            height: 300,
            columns: [
                  { field: "logInOwner", title: "Created User", filterable: true, width: "10em", editable: true },
          {
              field: "followUpdate", title: "Follow UpDate", filterable: false,
              editor: dateTimeEditor, width: "6em", format: "{0:MM/dd/yyyy HH:mm tt}",
              filterable: {
                  ui: "datetimepicker"
              }
          },
            {
                field: "communicationDate", title: "ChangedDate", filterable: false, width: "8em", format: "{0:MM/dd/yyyy HH:mm tt}",
                editor: dateTimeEditor,
                filterable: {
                    ui: "datetimepicker"
                }
            },
             { field: "company", title: "Company *", filterable: false, editor: companyDropDownEditor, width: "8em" },
              { field: "companyoffice", title: "Office *", editor: officeDropDownEditor, width: "8em" },
              { field: "product", title: "Products *", editor: productDropDownEditor, filterable: false, width: "8em" },
              { field: "commVia", title: "Contacted Via *", editor: contactedviaDropDownEditor, width: "8em" },
           { field: "CommEmployee", title: "Assigned Employee *", editor: invlouedEmployeeDropDownEditor, filterable: false, width: "8em" },
           { field: "phone", title: "Phone", width: "8em" },
           { field: "emailTo", title: "Email*", filterable: false, width: "8em" },
           { field: "statusName", title: "Status*", editor: statusDropDownEditor, filterable: false, width: "8em" },
          { field: "subject", title: "Subject", width: "8em" },
            {
                field: "notes", title: "Notes", width: "200px", editor: function (container, options) {
                    $('<textarea data-bind="value: ' + options.field + '" cols="20" rows="10"></textarea>').appendTo(container);
                }
            },
          {
              title: "&nbsp;",
              width: "25em",
              //command: ["edit", "destroy"]
              command: [

                  "edit",
                  {
                      name: "Delete",
                      click: function (e) {

                          var tr = $(e.target).closest("tr"); //get the row for deletion
                          var dataItem = this.dataItem(tr); //get the row data so it can be referred later
                          //see what is coming in dataItem
                          //if (dataItem > 0) {
                          //    $("#delValidation").addClass('in')
                          //}
                          //else {

                          deleteTopicConfirmation(e, this);
                          ////}
                          return false;
                      }
                  }
              ]
          }
            ],
            filterable: {
                extra: false,
                operators: {
                    string: {
                        eq: "Is equal to",
                        neq: "Is not equal to",
                        contains: "Contains"
                    }
                }
            },
            editable: "popup",
            sortable: {
                mode: "single",
                allowUnsort: false
            },
            selectable: true,
            cancel: function () {
                gridInEditMode = false;
            },
            edit: function (e) {
                //e.container.find("input:first").hide();
                debugger;
                editedUID = e.model.uid;
                assignedEmployeeIdVar = e.model.CommEmployeeIds;
                //e.model.companyId = e.model.clientID;
                setVisibilityOfFollowup(e.model.statusName);
            }
        });
        function companyDropDownEditor(container, options) {
            $('<input id="ProductValue" data-text-field="company" data-value-field="id"  data-bind="value:clientID"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                dataTextField: "company",
                dataSource: companydatasource,
                dataBound: function (e) {
                    //e.sender.value(assignedProductId);
                },
            });
        }
        function productDropDownEditor(container, options) {

            $('<input id="ProductValue" data-text-field="product" data-value-field="id"  data-bind="value:productID"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                dataTextField: "product",
                dataSource: productdatasource
            });
        }
        function statusDropDownEditor(container, options) {

            $('<input id="StatusValue" data-text-field="statusName" data-value-field="status"  data-bind="value:statusID"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "status",
                dataTextField: "statusName",
                dataSource: statusdatasource,
                change: function (e) {
                    setVisibilityOfFollowup(e.sender.text());
                },

            });
        }
        function setVisibilityOfFollowup(selectedValue) {
            if (selectedValue == "Follow Up") {
                $('div').find("[data-container-for=followUpdate]").prev().show();
                $('div').find("[data-container-for=followUpdate]").show();
            }
            else {
                $('div').find("[data-container-for=followUpdate]").prev().hide();
                $('div').find("[data-container-for=followUpdate]").hide();
            }
        }
        function contactedviaDropDownEditor(container, options) {

            $('<input id="ContactedViaValue" data-text-field="commVia" data-value-field="id"  data-bind="value:communicationTypeID"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "id",
                dataTextField: "commVia",
                dataSource: contactedviadatasource

            });
        }
        function officeDropDownEditor(container, options) {

            $('<input id="officeId" data-text-field="companyoffice" data-value-field="officeId"  data-bind="value:officeId"/>').appendTo(container).kendoDropDownList({
                autoBind: true,
                dataValueField: "officeId",
                dataTextField: "companyoffice",
                dataSource: officedatasource
            });
        }

        function invlouedEmployeeDropDownEditor(container, options) {
            $('<input id="invlouedEmployeeId"  data-bind="value:CommEmployeeIds" />').appendTo(container).kendoDropDownList({
                autoBind: false,
                dataValueField: "id",
                dataTextField: "InvoluedEname",
                dataSource: involuedEmployees,
                template: "<input type='checkbox' id='chk_AssEmp_#=data.id #' onclick='UpdateIdinIsAssEmp(this);' value='#=data.id #' name='chk_AssEmp' />" + " " + "${ data.InvoluedEname }",
                close: function (e) {
                    if (IsAssEmpChecked == true) {
                        IsAssEmpChecked = false;
                        e.preventDefault();
                    }
                    else {
                        var allVals = [];
                        $("input[id*='chk_AssEmp']:checked").each(function () {
                            allVals.push($(this).val());
                        });

                        var gridList = $("#MessageGrid").data("kendoGrid").dataSource.data();
                        for (var i = 0; i < gridList.length; i++) {
                            if (gridList[i].uid == editedUID) {
                                gridList[i].CommEmployeeIds = allVals.join(",");
                                break;
                            }
                        }

                        e.sender.text(allVals.length + " item(s) selected");
                    }
                },
                change: function (e) {
                    e.sender.value(null);
                },
                dataBound: function (e) {

                    var count = 0;
                    if (assignedEmployeeIdVar) {
                        assignedEmployeeIdVar = "," + assignedEmployeeIdVar + ",";
                        $("input[id*='chk_AssEmp']").each(function () {

                            if (assignedEmployeeIdVar.indexOf("," + $(this).val() + ",") != -1) {

                                $(this).attr('checked', 'checked');
                                count++;
                            }
                        });
                        assignedEmployeeIdVar = null;
                        e.sender.text(count + " item(s) selected");
                    }
                },
            });
        }

        dataSource3.bind("requestEnd", showSuccessMessage);
        function showSuccessMessage(e) {


            if (e.type === "update" || e.type === "create") {
                gridInEditMode = false;
                e.sender.read();
            }
        }
        $(".close").click(function () {
            $(this).parent().removeClass('in');
        });
        function deleteTopicConfirmation(e, widget) {
            var grid = $('#MessageGrid').data("kendoGrid");
            deleteConfirmation(e, widget, grid);
        }

        function deleteConfirmation(e, widget, grid) {

            var currentRow = $(e.target).closest("tr"); //get the row for deletion

            var currentRowData = widget.dataItem(currentRow); //get the row data so it can be  referred later

            var kendoWindow = $("<div />").kendoWindow({

                title: "Confirmation",
                resizable: true,
                modal: true,
                width: "400px"
            });

            kendoWindow.data("kendoWindow")

                .content($("#delete-confirmation").html())

                .center().open();

            kendoWindow

                .find(".delete-confirm,.delete-cancel")
                .click(function () {
                    if ($(this).hasClass("delete-confirm")) {

                        grid.dataSource.remove(currentRowData);

                        grid.dataSource.sync();

                    }

                    $(this).closest("[data-role=window]").kendoWindow("close");

                });

        }
    }
</script>

<script type="text/javascript" src="~/Scripts/CallCenter/AddContactsGrid.js"></script>
